<template>
    <div class="pie-chart shadow-box">
        <div class="header flex">
            <div class="header-left">
                <p>{{header.title}}</p>
            </div>
            <div class="header-right" v-if="header.router">
                <router-link :to="header.router">{{header.rightText}}&gt;</router-link>
            </div>
        </div>
        <div class="i-m-content" :style="{height: height + 'px'}">
            <div v-show="total !== 0" class="chart-box" ref="chartBox"></div>
            <div v-show="total === 0" class="statistics-no-data">
                <img src="static/images/statistics-no-data.png">
                <p>暂无数据</p>
            </div>
            <Spin size="large" fix v-if="loading"></Spin>
        </div>
    </div>
</template>

<script>
    import echarts from 'echarts/lib/echarts';
    import 'echarts/lib/component/tooltip';
    import 'echarts/lib/component/title';
    import 'echarts/lib/component/legendScroll';
    import 'echarts/lib/chart/pie'; //引入饼形图
    export default {
        props: {
            height: {
                type: [String, Number],
                default: 350
            },
            header: {  
                type: Object
            },
            chartTitle: '',
            optionColor: {  //颜色
                type: Array,
                default(){
                    return ['#ffad26', '#ff55ee', '#aadd33', '#fa6f33', '#aa5500', '#00aadd', '#00aa00']
                }
            },
            total: {
                type: [String, Number],
                default: 0
            },
            legend: {
                type: Object,
                default(){
                    return {
                        shape: 'circle', //react
                        data: ['超速', '急减速', '飞站', '带速开关门', '急加速', '哈哈哈', '嘿嘿嘿'],
                        itemWidth: 8,
                        itemHeight: 8,
                        itemGap: 12,    //每项之间的间距
                    }
                }, 
            },
            optionData: {   //图表数据
                type: Array,
                default(){
                    return [
                        {value: 835,name: '超速'}, 
                        {value: 335,name: '急减速'},
                        {value: 315,name: '飞站'}, 
                        {value: 200,name: '带速开关门'},
                        {value: 140,name: '急加速'},
                        {value: 650,name: '哈哈哈'},
                        {value: 1321,name: '嘿嘿嘿'},
                    ]
                }
            }
        },
        data(){
            return {
                echart: null,
                echartOption: null,
                allCount: 0,
                resizeTimer: null,
                loading: true
            }
        },
        mounted(){
            // this.init()
            window.addEventListener('resize', this.init)
        },
        destroyed(){
            window.removeEventListener('resize', this.init)
        },
        methods: {
            init(){
                this.$nextTick().then(()=>{
                    if(this.total == 0) return;
                    this.loading = false;
                    clearTimeout(this.resizeTimer);
                    this.resizeTimer = setTimeout(() => {
                        if(this.echart) this.echart.dispose();
                        this.echart = echarts.init(this.$refs.chartBox); //初始化图表
                        this.initOption()
                        this.echart.setOption(this.echartOption);
                    }, 300);
                })
            },
            initOption(){
                this.allCount = this.total;
                // for(let i=0, l=this.optionData.length; i<l; this.allCount += this.optionData[i++].value);
                let width = this.echart._dom.offsetWidth;
                this.echartOption = {
                    title: {
                        show: true,
                        text: `{title|总车辆数}\n{allCount|${this.allCount}}`,
                        left: width*25/100 - 72,
                        align: 'center',
                        top: '40%',
                        textStyle: {
                            // width: '100%',
                            rich: {
                                allCount: {
                                    align: 'center',
                                    color: '#333',
                                    fontSize: 28,
                                    lineHeight: 50,
                                    width: 140
                                },
                                title: {
                                    align: 'center',
                                    fontSize: 14,
                                    width: 140
                                }
                            }
                        }
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{b} : {c} ({d}%)"
                    },
                    color: this.optionColor,
                    legend: { //图例组件，颜色和名字
                        show:true,
                        left: '54%',
                        top: '15%',
                        orient: 'vertical',
                        itemGap: this.legend.itemGap, //图例每项之间的间隔
                        itemWidth: this.legend.itemWidth,
                        itemHeight: this.legend.itemHeight,
                        icon: this.legend.shape,
                        data: this.legend.data,
                        selectedMode: false,
                        formatter: this.legendFoematter,
                        textStyle: {
                            color: ['#666'],
                            fontSize: 12,
                            rich: {
                                name: {
                                    width: 80,
                                    color: '#666'
                                },
                                line: {
                                    color: '#ddd',
                                    padding: [0, 10, 0, 10]
                                },
                                percent: {
                                    width: 40,
                                    color: '#666'
                                },
                                count: {
                                    color: '#666',
                                    padding: [0, 10, 0, 20]
                                }
                            }
                        }
                    },
                    series: [{
                        name: '违规次数',
                        type: 'pie',
                        clockwise: false, //饼图的扇区是否是顺时针排布
                        minAngle: 1, //最小的扇区角度（0 ~ 360）
                        center: ['25%', '50%'], //饼图的中心（圆心）坐标
                        radius: ['56%', '75%'], //饼图的半径
                        avoidLabelOverlap: true, ////是否启用防止标签重叠
                        itemStyle: { //图形样式
                            normal: {
                                borderColor: '#fff',
                                borderWidth: 3,
                            }
                        },
                        label: { //标签的位置
                            normal: {
                                show: false,
                            }
                        },
                        data: this.optionData
                    }]
                }
            },
            legendFoematter(name){ //图例
                let data = this.optionData;
                for(let i=0; i<data.length; i++){
                    if(name === data[i].name){
                        let percent = data[i].percent ? //如果有百分比返回， 就用返回的百分比， 没有就用计算出来的
                            (String(data[i].percent).indexOf('.') > 0 ? (data[i].percent).toFixed(1) + '%' : data[i].percent + '%') : //如果有小数点， 取一位小数， 如果没有就直接用返回的数据
                                ((data[i].value/this.allCount)*100).toFixed(1) + '%';
                        let text = `{name|${name}}`;
                        text += `{line|\|}`;
                        text += `{percent|${percent}}`;
                        text += `{count|${data[i].value}}`;
                        return text;
                    }
                }
            }
        }
    }
</script>

<style lang="less" rel="stylesheet/less">
    .pie-chart{
        .chart-box{
            height: 100%;
        }
        .i-m-content{
            position: relative;
        }
    }
</style>